package com.woniu.execption.handler;

import com.woniu.model.Result;
import com.woniu.execption.goods.GoodsException;
import com.woniu.execption.goodstype.GoodsTypeException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalPointsmallExceptionHandler {


    @ExceptionHandler(GoodsException.class)
    public Result GoodsException(GoodsException e){
        e.printStackTrace();
        return Result.newInstance(null).setCode(e.getCode()).setMessage(e.getMessage());
    }


    @ExceptionHandler(GoodsTypeException.class)
    public Result GoodsTypeException(GoodsTypeException e){
        e.printStackTrace();
        return Result.newInstance(null).setCode(e.getCode()).setMessage(e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result AccountException(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder message = new StringBuilder();

        for (int i = 0; i < fieldErrors.size(); i++) {
            message.append(fieldErrors.get(i).getDefaultMessage());
            if (i < fieldErrors.size() - 1) {
                message.append(";");
            }
        }

        return Result.newInstance(null).setCode(500).setMessage(message.toString());
    }

    /**
     * 兜底操作
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result Exception(Exception e){
        e.printStackTrace();
        return Result.newInstance(null).setCode(500).setMessage(e.getMessage());
    }
}
